
import {getToken} from "@/utils/local";
import {ref} from "vue";
const wsClient = ref<WebSocket | null>(null);
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5;
const heartbeatInterval = ref<any>(null);
const sessionId = ref('');

interface WsMsgPayload {
  sessionId: string;
  timestamp: number
  event: EventEnum;
  data: any;
}
enum EventEnum {
  /**
   * 登录成功事件
   */
  SUCCEED = 'SUCCEED',

  /**
   * 心跳包事件
   */
  HEARTBEAT = 'HEARTBEAT',

  /**
   * 坐席状态变更事件
   */
  AGENT_STATUS = 'AGENT_STATUS',

  /**
   * 未知事件类型
   */
  UNKNOWN = 'UNKNOWN'


}

function getEventFromValue(value: string): EventEnum {
  const result = Object.values(EventEnum).find(
      (v) => v === value
  );

  return result as EventEnum || EventEnum.UNKNOWN;
}


export const initWebsocketClient = () => {
  const token = getToken();
  const wsUrl = `ws://localhost:4320/ws?token=${token}`;
  wsClient.value = new WebSocket(wsUrl);
  wsClient.value.onopen = () => {
    console.log('WebSocket连接已打开');
    sendHeartbeat();
  };
  wsClient.value.onmessage = (event) => {
    console.log('收到服务器消息:', event.data);
    const message = JSON.parse(event.data);
    switch (getEventFromValue(message.event)) {
      case EventEnum.SUCCEED:
        sessionId.value = message.sessionId;
        console.log('登录成功，sessionId:', message.sessionId);
        break;
      case EventEnum.HEARTBEAT:
        console.log('收到心跳包');
        break;
      case EventEnum.AGENT_STATUS:
        console.log('坐席状态变更:', message.data);
        break;
      default:
        console.log('未知事件类型:', message.event);
    }
  }
  wsClient.value.onclose = (event) => {
    console.log('WebSocket连接已关闭');
    //主动关闭不重试
    if (event.code === 1000) {
      console.log('主动关闭，不进行重连');
      return;
    }


    reconnectWebSocket();
  };
  wsClient.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
    wsClient.value?.close(); // 主动关闭异常连接
  };
};



const reconnectWebSocket = () => {
  if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
    console.error('WebSocket 重连失败，请检查网络');
    return;
  }

  setTimeout(() => {
    reconnectAttempts++;
    console.log(`第 ${reconnectAttempts} 次 WebSocket 重连`);
    initWebsocketClient();
  }, Math.min(1000 * Math.pow(2, reconnectAttempts), 10000));
};


const sendHeartbeat = () => {
  if (heartbeatInterval.value) clearInterval(heartbeatInterval.value);
  heartbeatInterval.value = setInterval(() => {
    if (wsClient.value && wsClient.value.readyState === WebSocket.OPEN) {
     const payload:WsMsgPayload = {
        sessionId: sessionId.value,
        timestamp: Date.now(),
        event: EventEnum.HEARTBEAT,
        data: {},
      };
      wsClient.value.send(JSON.stringify(payload));
    }
  }, 10000); // 每30秒发送一次心跳
};


export const closeWebSocket = () => {
  if (wsClient.value) {
    wsClient.value.close(1000);
  }
};

export const updateAgentStatus = (agentId: number,status: string) => {
  if (wsClient.value && wsClient.value.readyState === WebSocket.OPEN) {
    const payload:WsMsgPayload = {
      sessionId: sessionId.value,
      timestamp: Date.now(),
      event: EventEnum.AGENT_STATUS,
      data: {
        agentId: agentId,
        onlineStatus: status,
      },
    };
    wsClient.value.send(JSON.stringify(payload));
  }
};